package com.vitaf.cash.app.base

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.Fragment
import com.vitaf.cash.app.R
import com.vitaf.cash.app.utils.extensions.getColorRes
import com.vitaf.cash.app.utils.manager.VitafToastManager


/**
 * BaseFragment
 * @Author wwdeng
 * @CreateTime: 2024/11/22 10:32
 * @Annotation：基类 Fragment
 */
abstract class VitafBaseFmtV2: Fragment(), IVitafBaseView {
    /* 配置变量 */
    private var isInterceptBack = false
    private var mActivity: Activity? = null

    /** 关联的BaseActivity */
    private var baseActivity: VitafBaseActV2? = null

    // 获取页面名称，子类必须实现
    protected abstract val pageName: String
    // 是否启用页面埋点（默认启用）
    protected open val enablePageTrack: Boolean = true

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mActivity = activity
        if (activity is VitafBaseAct) {
            baseActivity = activity as VitafBaseActV2
        }
    }

    override fun onDetach() {
        super.onDetach()
        baseActivity = null
        mActivity = null
    }

    override fun getContext(): Context? {
        return mActivity
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return createVitafContentView(inflater)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (savedInstanceState != null) {
            return
        }
        // 初始化视图组件
        initializeVitafViews()
        setupVitafEventListeners()
        loadVitafData()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 清理资源
        baseActivity?.hideVitafLoading()
    }

    /**
     * 获取布局文件根视图
     */
    protected abstract fun createVitafContentView(inflater: LayoutInflater): View?

    /**
     * 初始化 View 控件
     */
    protected abstract fun initializeVitafViews()

    /**
     * 事件监听
     */
    protected abstract fun setupVitafEventListeners()

    /**
     * 加载数据
     */
    protected abstract fun loadVitafData()

    override fun showVitafLoading() {
        if (isFragmentActive()) {
            showVitafLoading(getString(R.string.loading))
        }
    }

    fun showVitafLoading(msg: String = "") {
        if (isFragmentActive()) {
            baseActivity?.showVitafLoading(msg)
        }
    }

    fun showVitafLoading(isTouchOut: Boolean, isCancel: Boolean, msg: String = "") {
        if (isFragmentActive()) {
            baseActivity?.showVitafLoading(isTouchOut = isTouchOut,isCancel = isCancel,msg = msg)
        }
    }

    override fun hideVitafLoading() {
        if (isFragmentActive()) {
            baseActivity?.hideVitafLoading()
        }
    }

    /**
     * toast
     * @param s
     */
    override fun showVitafToast(s: String?) {
        if (isFragmentActive()) {
            baseActivity?.showVitafToast(s) ?:
            VitafToastManager.showShortText(requireContext(), s)
        }
    }

    /**
     * 页面跳转（不带参数）
     * @param T
     */
    open fun onIntent(T: Class<*>?) {
        if (isFragmentActive()) {
            baseActivity?.onIntent(T) ?:
            startActivity(Intent(requireContext(), T))
        }
    }

    /**
     * 页面跳转（带参数）
     * @param T
     * @param bundle
     */
    open fun onIntent(T: Class<*>?, bundle: Bundle?) {
        if (isFragmentActive()) {
            baseActivity?.onIntent(T, bundle) ?:
            startActivity(Intent(requireContext(), T).apply {
                bundle?.let { putExtras(it) }
            })
        }
    }

    /* 隐藏键盘 */
    fun onHideSoftInput(v: View) {
        if (isFragmentActive()) {
            baseActivity?.onHideSoftInput(v) ?:
            run {
                val imm = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(v.windowToken, 0)
            }
        }
    }

    /**
     * 隐藏软键盘
     */
    fun onHideSoftInput() {
        if (isFragmentActive()) {
            baseActivity?.onHideSoftInput() ?:
            run {
                val view = requireActivity().currentFocus ?: requireActivity().window.decorView
                val imm = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(view.windowToken, 0)
            }
        }
    }

    /* 显示键盘 */
    fun onShowSoftInput(v: View) {
        if (isFragmentActive()) {
            baseActivity?.onShowSoftInput(v) ?:
            run {
                v.requestFocus()
                val imm = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.showSoftInput(v, 0)
            }
        }
    }

    /* 是否拦截返回按钮 */
    fun isInterceptBack(isBackExit: Boolean) {
        isInterceptBack = isBackExit
    }

    /* 返回 */
    open fun onBackAction() {
        if (!isInterceptBack) { // 不拦截，直接返回
            if (isFragmentActive()) {
                baseActivity?.onBackAction() ?: requireActivity().onBackPressed()
            }
        }
    }

    fun getColor(color: Int): Int {
        return requireContext().getColorRes(color)
    }

    /**
     * 检查Fragment是否处于活跃状态
     */
    private fun isFragmentActive(): Boolean {
        return isAdded && !isDetached && !isRemoving &&
                context != null &&
                activity != null && !requireActivity().isFinishing
    }

    /**
     * 获取关联的BaseActivity
     */
    protected fun getBaseActivity(): VitafBaseActV2? {
        return baseActivity
    }

    /**
     * 安全执行操作（避免Fragment状态异常）
     */
    protected fun safeRun(block: () -> Unit) {
        if (isFragmentActive()) {
            try {
                block()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}
